﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace Kiosk
{
    public class HashData
    {
        public static string hashData(string data)
        {
            SHA256 hasher = SHA256Managed.Create();
            byte[] hashedData = hasher.ComputeHash(Encoding.Unicode.GetBytes(data));
            StringBuilder sb = new StringBuilder(hashedData.Length *2);

            foreach (byte b in hashedData)
            {
                sb.AppendFormat("{0:x2}",b);
            }

            return sb.ToString();
        }
    
        public static string HashLogin(string userName, string password)
        {
            return hashData(String.Format("{0}{1}", userName.Substring(0, 4), password));
        }
        
        public static bool IsValidPassword(string userName, string password, string hashedPasswordFromDb)
        {
            return (String.Compare(hashedPasswordFromDb, HashLogin(userName, password)) == 0);
        }
        
        private static void Sample()
        {
            
            const string userName = "testuser";
            const string password = "password";
            const string badPassword = "pa55w0rd";
            
            string hashedPassword = HashLogin(userName, password);
            
            Console.WriteLine("For user {0}, password {1}, hashed password is {2}", userName, password, hashedPassword);
            Console.WriteLine("Checking bad password {0}: {1}", badPassword, IsValidPassword(userName, badPassword, hashedPassword) ? "succeeded" : "failed");
            Console.WriteLine("Checking good password {0}: {1}", password, IsValidPassword(userName, password, hashedPassword) ? "succeeded" : "failed");
        }
    }
}
